package com.yunfeisoft.controller.business;

import com.applet.base.BaseController;
import com.applet.utils.*;
import com.yunfeisoft.business.model.AllotItem;
import com.yunfeisoft.business.model.AllotOrder;
import com.yunfeisoft.business.model.Warehouse;
import com.yunfeisoft.business.service.inter.AllotItemService;
import com.yunfeisoft.business.service.inter.AllotOrderService;
import com.yunfeisoft.business.service.inter.CodeBuilderService;
import com.yunfeisoft.business.service.inter.WarehouseService;
import com.yunfeisoft.model.User;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * ClassName: AllotOrderController
 * Description: 调拨单信息Controller
 * Author: Jackie liu
 * Date: 2020-08-06
 */
@Controller
public class AllotOrderController extends BaseController {

    @Autowired
    private AllotOrderService allotOrderService;
    @Autowired
    private CodeBuilderService codeBuilderService;
    @Autowired
    private AllotItemService allotItemService;
    @Autowired
    private WarehouseService warehouseService;

    /**
     * 添加调拨单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/allotOrder/save", method = RequestMethod.POST)
    @ResponseBody
    public Response save(AllotOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "outWarehouseId", "调出仓库为空");
        validator.required(request, "inWarehouseId", "调入仓库为空");
        validator.required(request, "allotDate", "调拨日期为空");
        validator.required(request, "productsStr", "商品为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        if (record.getOutWarehouseId().equals(record.getInWarehouseId())) {
            return ResponseUtils.warn("调出仓库和调入仓库相同");
        }
        User user = ApiUtils.getLoginUser();
        record.setId(KeyUtils.getKey());
        record.setOrgId(user.getOrgId());

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<AllotItem> allotItemList = FastJsonUtils.jsonToList(productsStr, AllotItem.class);

        BigDecimal totalAmount = BigDecimal.ZERO;
        Iterator<AllotItem> iterator = allotItemList.iterator();
        while (iterator.hasNext()) {
            AllotItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setAllotOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getQuantity() == null) {
                return ResponseUtils.warn("含有数量不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                return ResponseUtils.warn("含有进货价不合法或者为空的商品");
            }

            item.setAmount(item.getPrice().multiply(item.getQuantity()));
            totalAmount = totalAmount.add(item.getAmount());
        }
        record.setTotalAmount(totalAmount);
        record.setAllotItemList(allotItemList);
        if (CollectionUtils.isEmpty(allotItemList)) {
            return ResponseUtils.warn("商品为空");
        }

        String code = codeBuilderService.generateAllotOrderCode(user.getOrgId());
        record.setCode(code);
        record.setStatus(AllotOrder.AllotOrderStatusEnum.ALLOTED.getValue());

        allotOrderService.save(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 修改调拨单信息
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/allotOrder/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(AllotOrder record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "id", "参数错误");
        validator.required(request, "outWarehouseId", "调出仓库为空");
        validator.required(request, "inWarehouseId", "调入仓库为空");
        validator.required(request, "allotDate", "调拨日期为空");
        validator.required(request, "productsStr", "商品为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }
        if (record.getOutWarehouseId().equals(record.getInWarehouseId())) {
            return ResponseUtils.warn("调出仓库和调入仓库相同");
        }

        /*AllotOrder allotOrder = allotOrderService.load(record.getId());
        if (allotOrder.getStatus() != AllotOrder.AllotOrderStatusEnum.TO_BE_ALLOTED.getValue()
                && allotOrder.getStatus() != AllotOrder.AllotOrderStatusEnum.TO_BE_CHANGED.getValue()) {
            return ResponseUtils.warn("该订单状态不是【待调拨】，也不是【待更改】，无法修改");
        }*/

        User user = ApiUtils.getLoginUser();

        String productsStr = ServletRequestUtils.getStringParameter(request, "productsStr", null);
        List<AllotItem> allotItemList = FastJsonUtils.jsonToList(productsStr, AllotItem.class);

        BigDecimal totalAmount = BigDecimal.ZERO;
        Iterator<AllotItem> iterator = allotItemList.iterator();
        while (iterator.hasNext()) {
            AllotItem item = iterator.next();
            if (StringUtils.isBlank(item.getProductId())) {
                iterator.remove();
                continue;
            }
            item.setId(KeyUtils.getKey());
            item.setOrgId(user.getOrgId());
            item.setAllotOrderId(record.getId());

            if (StringUtils.isBlank(item.getWarehouseId())) {
                return ResponseUtils.warn("含有仓库为空的商品");
            }

            if (item.getQuantity() == null) {
                return ResponseUtils.warn("含有数量不合法或者为空的商品");
            }

            if (item.getPrice() == null) {
                return ResponseUtils.warn("含有进货价不合法或者为空的商品");
            }

            item.setAmount(item.getPrice().multiply(item.getQuantity()));
            totalAmount = totalAmount.add(item.getAmount());
        }
        record.setTotalAmount(totalAmount);
        record.setAllotItemList(allotItemList);
        if (CollectionUtils.isEmpty(allotItemList)) {
            return ResponseUtils.warn("商品为空");
        }
        record.setStatus(AllotOrder.AllotOrderStatusEnum.ALLOTED.getValue());

        allotOrderService.modify(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 查询调拨单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/allotOrder/query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response query(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        AllotOrder record = allotOrderService.load(id);

        if (record != null) {
            Warehouse outWarehouse = warehouseService.load(record.getOutWarehouseId());
            record.setOutWarehouseName(outWarehouse.getName());

            Warehouse inWarehouse = warehouseService.load(record.getInWarehouseId());
            record.setInWarehouseName(inWarehouse.getName());

            List<AllotItem> allotItemList = allotItemService.queryByAllotOrderId(id);
            record.setAllotItemList(allotItemList);
        }
        return ResponseUtils.success(record);
    }

    /**
     * 分页查询调拨单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/allotOrder/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response list(HttpServletRequest request, HttpServletResponse response) {
        String outWarehouseId = ServletRequestUtils.getStringParameter(request, "outWarehouseId", null);
        String inWarehouseId = ServletRequestUtils.getStringParameter(request, "inWarehouseId", null);

        User user = ApiUtils.getLoginUser();

        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("orgId", user.getOrgId());
        params.put("outWarehouseId", outWarehouseId);
        params.put("inWarehouseId", inWarehouseId);

        Page<AllotOrder> page = allotOrderService.queryPage(params);
        return ResponseUtils.success(page);
    }

    /**
     * 批量删除调拨单信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/allotOrder/delete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response delete(HttpServletRequest request, HttpServletResponse response) {
        String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
        if (StringUtils.isBlank(ids)) {
            return ResponseUtils.warn("参数错误");
        }
        allotOrderService.remove(ids.split(","));
        return ResponseUtils.success("删除成功");
    }

    /**
     * 改单解锁
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/web/allotOrder/changeOrder", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response changeOrder(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        AllotOrder allotOrder = allotOrderService.load(id);
        if (allotOrder.getStatus() != AllotOrder.AllotOrderStatusEnum.ALLOTED.getValue()) {
            return ResponseUtils.success("success");
        }

        allotOrderService.modifyWithUnLock(id, allotOrder);
        return ResponseUtils.success("success");
    }*/
}
